﻿using CommonType;
using MediatR;
using Microsoft.AspNetCore.Mvc.RazorPages;
using S_Gridding.Domains.BasicData;
using S_Gridding.Infrastructure.Dapper;
using S_Gridding.Infrastructure.Interface;
using S_Gridding.Read.Api.Command;

namespace S_Gridding.Read.Api.CommandHands
{
    /// <summary>
    /// 使用Dapper实现显示、分页功能
    /// </summary>
    public class ShowMeshTypeCommandHander : IRequestHandler<ShowMeshTypeCommand, PageResule<MeshTypeInfo>>
    {
        private readonly IDapperMeshTypeRepository _dapperMeshTypeRepository;

        public ShowMeshTypeCommandHander(IDapperMeshTypeRepository dapperMeshTypeRepository)
        {
            _dapperMeshTypeRepository = dapperMeshTypeRepository;
        }
        public async Task<PageResule<MeshTypeInfo>> Handle(ShowMeshTypeCommand request, CancellationToken cancellationToken)
        {
            var query = $"select * from MeshTypeInfo where 1=1";

            if(!string.IsNullOrEmpty(request.MeshTypeName))
            {
                query += $" and MeshTypeName like '%{request.MeshTypeName}%'";
            }

            var totalCount = await _dapperMeshTypeRepository.SelectAsync(request.PageSize, query);

            query += $" order by MeshTypeId desc limit {(request.PageIndex - 1) * request.PageSize},@PageSize;";

            var List=await _dapperMeshTypeRepository.SelectAsync(request.PageSize, query);

            return new PageResule<MeshTypeInfo>
            {
                TotalCount = totalCount.Count(),
                PageCount = (int)Math.Ceiling((List.Count() * 1.0) / request.PageSize),
                Data = List
            };
        }
    }
}
